package com.neutech.service.impl;

import com.neutech.entity.OrderItem;
import com.neutech.entity.Product;
import com.neutech.enumeration.ResultExceptionEnum;
import com.neutech.mapper.OrderItemMapper;
import com.neutech.service.OrderItemService;
import com.neutech.service.ProductService;
import com.neutech.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class OrderItemServiceImpl implements OrderItemService {
    private final OrderItemMapper mapper;
    private final ProductService productService;

    @Autowired
    public OrderItemServiceImpl(OrderItemMapper mapper, ProductService productService) {
        this.mapper = mapper;
        this.productService = productService;
    }

    @Override
    public ResultVO<List<OrderItem>> getOrderItemByOrderNo(Long orderNo) {
        List<OrderItem> items = mapper.selectAllByOrderNo(orderNo);
        if (items.isEmpty()) {
            return ResultVO.error(ResultExceptionEnum.DATA_NON_EXISTS);
        }
        return ResultVO.success(items);
    }

    @Override
    public ResultVO<Void> addOrderItem(Integer userId, Long orderNo, Integer productId, Integer quantity) {
        ResultVO<Product> pResultVO = productService.getProduct(productId);
        if (pResultVO.getCode() != 0) return ResultVO.error(ResultExceptionEnum.DATA_NON_EXISTS);
        Product product = pResultVO.getData();

        BigDecimal currentUnitPrice = product.getPrice();

        OrderItem orderItem = new OrderItem();

        orderItem.setUserId(userId);
        orderItem.setOrderNo(orderNo);
        orderItem.setProductId(productId);
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getMainImage());
        orderItem.setCurrentUnitPrice(currentUnitPrice);
        orderItem.setQuantity(quantity);
        orderItem.setTotalPrice(currentUnitPrice.multiply(new BigDecimal(quantity)));
        orderItem.setCreateTime(new Date());

        Integer code = mapper.insertSelective(orderItem);
        if (code.equals(1)) return ResultVO.success();
        else return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);
    }

    @Override
    public ResultVO<Void> addOrderItems(List<OrderItem> itemList) {
        int resultCode = mapper.insertBatch(itemList);
        if (resultCode == itemList.size()) return ResultVO.success();
        else return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);
    }
}
